

package com.hazelcast.spi.impl.executionservice.impl;

import com.hazelcast.internal.util.Clock;
import com.hazelcast.map.impl.ExecutorStats;

public class StatsAwareRunnable implements Runnable {

    private final long creationTime = Clock.currentTimeMillis();
    private final Runnable runnable;
    private final String executorName;
    private final ExecutorStats offloadedExecutorStats;

    public StatsAwareRunnable(Runnable runnable, String executorName, ExecutorStats offloadedExecutorStats) {
        this.runnable = runnable;
        this.executorName = executorName;
        this.offloadedExecutorStats = offloadedExecutorStats;

        offloadedExecutorStats.startPending(executorName);
    }

    @Override
    public void run() {
        long start = Clock.currentTimeMillis();
        offloadedExecutorStats.startExecution(executorName, start - creationTime);

        try {
            runnable.run();
        } finally {
            offloadedExecutorStats.finishExecution(executorName, Clock.currentTimeMillis() - start);
        }
    }
}
